package com.cskaoyan.service.wx.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.WXGoodsListVO;
import com.cskaoyan.bean.vo.wx.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.wx.WXGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Can
 * @since 2022/06/28 17:25
 */
@Service
public class WXGoodsServiceImpl implements WXGoodsService {

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    @Autowired
    MarketAdMapper marketAdMapper;

    @Autowired
    MarketBrandMapper marketBrandMapper;

    @Autowired
    MarketTopicMapper marketTopicMapper;

    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;

    @Autowired
    MarketIssueMapper marketIssueMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketCollectMapper marketCollectMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    /**
     * 获取 wx 首页 数据
     * 三个表 coupon category ad
     *
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 17:58
     */
    @Override
    public BaseRespVo getHomeInfo() {

        // 获取adList  banner
        MarketAdExample adExample = new MarketAdExample();
        adExample.createCriteria().andDeletedEqualTo(false).andEnabledEqualTo(true);
        List<MarketAd> banner = marketAdMapper.selectByExample(adExample);

        // 获取categoryList  channel
        List<InnerCategoryOfWXHomeInfoVo> channel = marketCategoryMapper.selectWXHomeInfoData();

        // 获取couponList
        MarketCouponExample couponExample = new MarketCouponExample();
        couponExample.createCriteria().andDeletedEqualTo(false).andStatusEqualTo((short) 0).andTypeEqualTo((short) 0);
        List<MarketCoupon> couponList = marketCouponMapper.selectByExample(couponExample);
        Collections.shuffle(couponList);
        couponList = couponList.stream().limit(3).collect(Collectors.toList());

        // 获取brandList
        MarketBrandExample brandExample = new MarketBrandExample();
        brandExample.createCriteria().andDeletedEqualTo(false);
        List<MarketBrand> brandList = marketBrandMapper.selectByExample(brandExample);
        if (brandList.size() > 10) {
            Collections.shuffle(brandList);
            brandList = brandList.subList(0, 10);
        }

        // 获取topicList
        MarketTopicExample topicExample = new MarketTopicExample();
        topicExample.createCriteria().andDeletedEqualTo(false);
        List<MarketTopic> topicList = marketTopicMapper.selectByExample(topicExample);
        if (topicList.size() > 10) {
            Collections.shuffle(topicList);
            topicList = topicList.subList(0, 10);
        }

        // 获取floorGoodsList
        List<InnerFloorGoodsOfWXHomeInfoVo> floorGoodsList = new ArrayList<>();
        for (InnerCategoryOfWXHomeInfoVo category : channel) {
            InnerFloorGoodsOfWXHomeInfoVo floorGoods = new InnerFloorGoodsOfWXHomeInfoVo(null, category.getId(), category.getName());
            // 先通过category 一级id 查出所有的 二级id
            List<Integer> levelTwoIdList = marketCategoryMapper.selectLevelTwoIdByLevelOneId(category.getId());
            if (levelTwoIdList.size() != 0) {
                // 通过二级id 查出所有的商品
                MarketGoodsExample goodsExample = new MarketGoodsExample();
                goodsExample.createCriteria().andDeletedEqualTo(false).andCategoryIdIn(levelTwoIdList);
                List<MarketGoods> goodsList = marketGoodsMapper.selectByExample(goodsExample);
                if (goodsList.size() > 10) {
                    Collections.shuffle(goodsList);
                    goodsList = goodsList.subList(0, 10);
                }
                floorGoods.setGoodsList(goodsList);
            }
            // 添加至floorGoodsList
            floorGoodsList.add(floorGoods);
        }

        // 获取hotGoodsList
        MarketGoodsExample hotGoodsExample = new MarketGoodsExample();
        hotGoodsExample.createCriteria().andDeletedEqualTo(false).andIsHotEqualTo(true);
        List<MarketGoods> hotGoodsList = marketGoodsMapper.selectByExample(hotGoodsExample);
        if (hotGoodsList.size() > 6) {
            Collections.shuffle(hotGoodsList);
            hotGoodsList = hotGoodsList.subList(0, 6);
        }

        // 获取newGoodsList
        MarketGoodsExample newGoodsExample = new MarketGoodsExample();
        newGoodsExample.createCriteria().andDeletedEqualTo(false).andIsNewEqualTo(true);
        List<MarketGoods> newGoodsList = marketGoodsMapper.selectByExample(newGoodsExample);
        if (newGoodsList.size() > 6) {
            Collections.shuffle(newGoodsList);
            newGoodsList = newGoodsList.subList(0, 6);
        }
        WXHomeInfoVo homeInfoVo = new WXHomeInfoVo(banner, channel, couponList, floorGoodsList, brandList, topicList, hotGoodsList, newGoodsList);
        return BaseRespVo.ok(homeInfoVo);
    }

    /**
     * 获取商品数量
     *
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 20:31
     */
    @Override
    public BaseRespVo countGoods() {
        int count = marketGoodsMapper.selectCountGoods();
        return BaseRespVo.ok(count);
    }

    /**
     * 通过类别id 获取所有的二级类别
     * 这个id 有可能是一级id 有可能是二级id
     *
     * @param categoryId
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 21:01
     */
    @Override
    public BaseRespVo getCategories(Integer categoryId) {
        // 这个id 有可能是一级id 有可能是二级id 需要判断
        MarketCategory parentCategory;
        MarketCategory currentCategory;
        List<MarketCategory> brotherCategory;

        MarketCategory category = marketCategoryMapper.selectByPrimaryKey(categoryId);
        if (category.getPid() == 0) {
            // 类别id是一级id
            parentCategory = category;

            // 所有二级类别
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andDeletedEqualTo(false).andPidEqualTo(categoryId);
            brotherCategory = marketCategoryMapper.selectByExample(categoryExample);

            // 当前类别
            currentCategory = brotherCategory.get(0);
        } else {
            // 类别id是二级id
            currentCategory = category;

            // 一级类别
            parentCategory = marketCategoryMapper.selectByPrimaryKey(currentCategory.getPid());

            // 所有二级类别
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andDeletedEqualTo(false).andPidEqualTo(currentCategory.getPid());
            brotherCategory = marketCategoryMapper.selectByExample(categoryExample);
        }

        WXGetCategoriesByCategoryIdVo categoryVo = new WXGetCategoriesByCategoryIdVo(brotherCategory, currentCategory, parentCategory);
        return BaseRespVo.ok(categoryVo);
    }

    /**
     * 通过类别id获取商品列表
     *
     * @param categoryId
     * @param page
     * @param limit
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 21:54
     */
    @Override
    public BaseRespVo getGoodsListByCategoryId(Integer categoryId, Integer page, Integer limit) {
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false).andCategoryIdEqualTo(categoryId);

        PageHelper.startPage(page, limit);
        List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(list);
        CommonData data = CommonData.data(pageInfo);

        return BaseRespVo.ok(data);
    }

    /**
     * 通过品牌id获取商品列表
     *
     * @param brandId
     * @param page
     * @param limit
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 21:55
     */
    @Override
    public BaseRespVo getGoodsListByBrandId(Integer brandId, Integer page, Integer limit) {

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false).andBrandIdEqualTo(brandId);

        PageHelper.startPage(page, limit);
        List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(list);
        CommonData data = CommonData.data(pageInfo);

        return BaseRespVo.ok(data);
    }

    /**
     * 获取商品推荐列表
     *
     * @param id
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 22:28
     */
    @Override
    public BaseRespVo getRelatedGoodsList(Integer id) {
        MarketGoods goods = marketGoodsMapper.selectByPrimaryKey(id);

        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(goods.getCategoryId()).andDeletedEqualTo(false);

        PageHelper.startPage(1, 6);
        List<MarketGoods> list = marketGoodsMapper.selectByExample(goodsExample);

        PageInfo<MarketGoods> goodsPageInfo = new PageInfo<>(list);
        CommonData data = CommonData.data(goodsPageInfo);
        return BaseRespVo.ok(data);
    }

    /**
     * 获取商品详情
     *
     * @param goodsId 商品id
     * @return com.cskaoyan.bean.vo.BaseRespVo
     * @author Can
     * @since 2022/06/28 22:59
     */
    @Override
    public BaseRespVo getGoodsDetail(Integer goodsId) {
        // 获取attribute表
        List<MarketGoodsAttribute> attribute = marketGoodsAttributeMapper.selectByGoodsId(goodsId);

        // 获取info goods表中数据
        MarketGoods info = marketGoodsMapper.selectByPrimaryKey(goodsId);

        // 获取brand
        MarketBrand brand = marketBrandMapper.selectByPrimaryKey(info.getBrandId());

        // 获取issue
        MarketIssueExample issueExample = new MarketIssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        List<MarketIssue> issue = marketIssueMapper.selectByExample(issueExample);

        // 获取productList
        List<MarketGoodsProduct> productList = marketGoodsProductMapper.selectByGoodId(goodsId);

        // 获取userHasCollect
        // 通过subject获取userId 在通过goodsId和userId查找
        // 如果没有登录 默认是0
        byte userHasCollect = 0;
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipal();
        if (marketUser != null) {
            Integer userId = marketUser.getId();

            MarketCollectExample collectExample = new MarketCollectExample();
            collectExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andValueIdEqualTo(goodsId).andTypeEqualTo((byte) 0);

            List<MarketCollect> marketCollectList = marketCollectMapper.selectByExample(collectExample);
            userHasCollect = (byte) marketCollectList.size();
        }

        // 获取分享图片
        String shareImage = info.getShareUrl();

        // 获取comment
        // 随机取三条
        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andDeletedEqualTo(false).andValueIdEqualTo(goodsId).andTypeEqualTo((byte) 0);
        List<MarketComment> data = marketCommentMapper.selectByExample(commentExample);
        InnerCommentOfWXGoodsDetailVo comment = new InnerCommentOfWXGoodsDetailVo();
        comment.setCount(data.size());
        Collections.shuffle(data);
        if (data.size() > 3) {
            data = data.subList(0, 3);
        }
        comment.setData(data);

        // 获取specificationList
        List<MarketGoodsSpecification> allSpecifications = marketGoodsSpecificationMapper.selectByGoodsId(goodsId);
        List<String> names = allSpecifications.stream().map(MarketGoodsSpecification::getSpecification).distinct().collect(Collectors.toList());

        List<InnerSpecificationOfWXGoodsDetailVo> specificationList = new ArrayList<>();
        for (String name : names) {
            List<MarketGoodsSpecification> valueList = allSpecifications.stream().filter(spec -> spec.getSpecification().equals(name)).collect(Collectors.toList());

            InnerSpecificationOfWXGoodsDetailVo specificationOfWXGoodsDetailVo = new InnerSpecificationOfWXGoodsDetailVo();
            specificationOfWXGoodsDetailVo.setName(name);
            specificationOfWXGoodsDetailVo.setValueList(valueList);
            specificationList.add(specificationOfWXGoodsDetailVo);
        }

        WXGoodsDetailVo goodsDetailVo = new WXGoodsDetailVo(attribute, brand, info, issue, productList, userHasCollect, shareImage, comment, specificationList);

        return BaseRespVo.ok(goodsDetailVo);
    }

    /**
     * 新品首发页面
     *
     * @param categoryId
     * @param info
     * @param isHot
     * @param isNew
     * @return com.cskaoyan.bean.BaseRespVo
     * @author Can
     * @since 2022/06/29 22:45
     */
    @Override
    public BaseRespVo getNewOrHotGoodsList(Integer categoryId, BasePageInfo info, Boolean isHot, Boolean isNew) {
        MarketCategoryExample categoryExample = new MarketCategoryExample();
        categoryExample.createCriteria().andDeletedEqualTo(false).andLevelEqualTo("L2");
        List<MarketCategory> categoryList = marketCategoryMapper.selectByExample(categoryExample);
        Collections.shuffle(categoryList);
        List<MarketCategory> filterCategoryList = categoryList.subList(0, 10);

        String orderByClause = info.getSort() + " " + info.getOrder();
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.setOrderByClause(orderByClause);
        MarketGoodsExample.Criteria criteria = goodsExample.createCriteria().andDeletedEqualTo(false);
        if (categoryId != 0) {
            criteria.andCategoryIdEqualTo(categoryId);
        }
        if (isHot != null) {
            criteria.andIsHotEqualTo(true);
        }
        if (isNew != null) {
            criteria.andIsNewEqualTo(true);
        }
        PageHelper.startPage(info.getPage(), info.getLimit());
        List<MarketGoods> list = marketGoodsMapper.selectByExampleWithBLOBs(goodsExample);


        PageInfo<MarketGoods> goodsPageInfo = new PageInfo<>(list);
        WXGoodsListVO data = WXGoodsListVO.data(goodsPageInfo);
        data.setFilterCategoryList(filterCategoryList);

        return BaseRespVo.ok(data);
    }
}
